<template>
  <div>
    <mt-header title="搜索地址" :fixed="true">
      <router-link style="text-decoration: none;" to="/editaddress" slot="left">
        <span class="iconfont icon-go-back"></span>
      </router-link>
    </mt-header>
    <div class="search-box">
      <span class="iconfont icon-sousuo"></span>
      <input class="search-inp" v-model="keyword" placeholder="请输入小区/写字楼/学校等" />
      <button class="search-btn">搜索</button>
    </div>
    <div class="show-result">
      <div class="result-item" v-for="item in addrList" :key="item.id" @click="storageAddrInfo(item)">
        <p class="addr-name">{{item.name}}</p>
        <p class="addr-desc">{{item.address}}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { searchAddr } from '@/api/elm-data'
export default {
  name: 'search-addr',
  data() {
    return {
      addrList: [],
      keyword: ''
    }
  },
  methods: {
    async searchAddress(keyword) {
      const { data } = await searchAddr(keyword)
      console.log(data)
      this.addrList = data
    },
    storageAddrInfo(info) {
      this.$route.query.address = info.name,
      this.$route.query.address_detail = info.address,
      this.$router.replace({name: 'editaddress', query: this.$route.query })
    }
  },
  watch: {
    keyword() {
      if(this.keyword !== '') {
        this.searchAddress(this.keyword)
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    if(from.path === '/editaddress' || from.path === '/') {
      next()
    }else {
      if(window.sessionStorage.getItem('token')) {
        next('/index')
      }else {
        next('/login')
      }
    }
  }
}
</script>

<style scoped>
  .search-box {
    margin-top: 76px;
    padding: 5px 30px;
    background-color: #fff;
    position: relative;
  }
  .search-inp {
    width: 550px;
    height: 50px;
    padding-left: 40px;
    border: none;
    background-color: #e8e8e8;
    box-sizing: border-box;
    color: #818181;
  }
  .search-btn {
    width: 100px;
    padding: 10px;
    margin-left: 20px;
    background-color: #0097FF;
    border: none;
    color: #fff;
  }
  .icon-sousuo {
    position: absolute;
    left: 40px;
    top: 14px;
    font-size: 30px;
  }
  .show-result {
    padding: 40px 20px;
    min-height: calc(100vh - 220px);
    background-color: #fff;
  }
  .result-item {
    border-bottom: 1px solid #EEE;
  }
  .addr-name {
    font-size: 32px;
    margin: 0;
    color: #444444;
  }
  .addr-desc {
    margin-top: 5px;
    font-size: 24px;
    color: #888888;
  }
</style>
